//! 索引系统模块
//! 
//! 提供B+树索引、哈希索引和复合索引等数据结构

pub mod btree;
pub mod hash;
pub mod composite;

#[cfg(test)]
mod simple_test;

use crate::{Error, Result};
use crate::sql::Value;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};

pub use btree::BPlusTree;
pub use hash::{HashIndex, HashStatistics};
pub use composite::{CompositeIndex, CompositeIndexType, CompositeKey, CompositeIndexStats};

/// 索引管理器
#[derive(Debug)]
pub struct IndexManager {
    /// 单列索引
    single_indexes: HashMap<String, SingleIndex>,
    /// 复合索引
    composite_indexes: HashMap<String, CompositeIndex>,
    /// 下一个索引ID
    next_index_id: AtomicU64,
    /// 全局统计信息
    stats: IndexManagerStats,
}

/// 单列索引
#[derive(Debug)]
pub enum SingleIndex {
    /// B+树索引
    BTree {
        column: String,
        index: BPlusTree,
    },
    /// 哈希索引
    Hash {
        column: String,
        index: HashIndex,
    },
}

/// 索引管理器统计信息
#[derive(Debug, Clone, Default)]
pub struct IndexManagerStats {
    /// 总索引数
    pub total_indexes: usize,
    /// 单列索引数
    pub single_indexes: usize,
    /// 复合索引数
    pub composite_indexes: usize,
    /// 总查找次数
    pub total_lookups: u64,
    /// 总插入次数
    pub total_inserts: u64,
    /// 总删除次数
    pub total_deletes: u64,
    /// 缓存命中次数
    pub cache_hits: u64,
    /// 缓存未命中次数
    pub cache_misses: u64,
}

impl IndexManager {
    /// 创建新的索引管理器
    pub fn new() -> Self {
        Self {
            single_indexes: HashMap::new(),
            composite_indexes: HashMap::new(),
            next_index_id: AtomicU64::new(1),
            stats: IndexManagerStats::default(),
        }
    }
    
    /// 创建B+树索引
    pub fn create_btree_index(&mut self, name: String, column: String) -> Result<()> {
        if self.single_indexes.contains_key(&name) || self.composite_indexes.contains_key(&name) {
            return Err(Error::index(format!("索引 {} 已存在", name)));
        }
        
        let btree = BPlusTree::new(100); // 度数100
        let index = SingleIndex::BTree { column, index: btree };
        
        self.single_indexes.insert(name, index);
        self.update_stats();
        
        Ok(())
    }
    
    /// 创建哈希索引
    pub fn create_hash_index(&mut self, name: String, column: String) -> Result<()> {
        if self.single_indexes.contains_key(&name) || self.composite_indexes.contains_key(&name) {
            return Err(Error::index(format!("索引 {} 已存在", name)));
        }
        
        let hash = HashIndex::new(256); // 256个桶
        let index = SingleIndex::Hash { column, index: hash };
        
        self.single_indexes.insert(name, index);
        self.update_stats();
        
        Ok(())
    }
    
    /// 创建复合索引
    pub fn create_composite_index(
        &mut self,
        name: String,
        columns: Vec<String>,
        index_type: CompositeIndexType,
    ) -> Result<()> {
        if self.single_indexes.contains_key(&name) || self.composite_indexes.contains_key(&name) {
            return Err(Error::index(format!("索引 {} 已存在", name)));
        }
        
        let composite_index = CompositeIndex::new(name.clone(), columns, index_type)?;
        self.composite_indexes.insert(name, composite_index);
        self.update_stats();
        
        Ok(())
    }
    
    /// 插入到单列索引
    pub fn insert_single(&mut self, index_name: &str, key: Value, row_id: usize) -> Result<()> {
        if let Some(index) = self.single_indexes.get_mut(index_name) {
            match index {
                SingleIndex::BTree { index: btree, .. } => {
                    btree.insert(key, row_id)?;
                }
                SingleIndex::Hash { index: hash, .. } => {
                    hash.insert(key, row_id)?;
                }
            }
            self.stats.total_inserts += 1;
            Ok(())
        } else {
            Err(Error::index(format!("索引 {} 不存在", index_name)))
        }
    }
    
    /// 插入到复合索引
    pub fn insert_composite(
        &mut self,
        index_name: &str,
        values: Vec<Value>,
        row_id: usize,
    ) -> Result<()> {
        if let Some(index) = self.composite_indexes.get_mut(index_name) {
            index.insert(values, row_id)?;
            self.stats.total_inserts += 1;
            Ok(())
        } else {
            Err(Error::index(format!("复合索引 {} 不存在", index_name)))
        }
    }
    
    /// 从单列索引查找
    pub fn lookup_single(&mut self, index_name: &str, key: &Value) -> Result<Option<usize>> {
        if let Some(index) = self.single_indexes.get(index_name) {
            self.stats.total_lookups += 1;
            
            let result = match index {
                SingleIndex::BTree { index: btree, .. } => btree.search(key),
                SingleIndex::Hash { index: hash, .. } => hash.lookup(key),
            };
            
            if result.is_some() {
                self.stats.cache_hits += 1;
            } else {
                self.stats.cache_misses += 1;
            }
            
            Ok(result)
        } else {
            Err(Error::index(format!("索引 {} 不存在", index_name)))
        }
    }
    
    /// 从复合索引查找
    pub fn lookup_composite(
        &mut self,
        index_name: &str,
        values: Vec<Value>,
    ) -> Result<Option<usize>> {
        if let Some(index) = self.composite_indexes.get_mut(index_name) {
            self.stats.total_lookups += 1;
            let result = index.lookup(values)?;
            
            if result.is_some() {
                self.stats.cache_hits += 1;
            } else {
                self.stats.cache_misses += 1;
            }
            
            Ok(result)
        } else {
            Err(Error::index(format!("复合索引 {} 不存在", index_name)))
        }
    }
    
    /// 范围查询（仅B+树索引支持）
    pub fn range_lookup_single(
        &self,
        index_name: &str,
        start: &Value,
        end: &Value,
    ) -> Result<Vec<usize>> {
        if let Some(index) = self.single_indexes.get(index_name) {
            match index {
                SingleIndex::BTree { index: btree, .. } => {
                    Ok(btree.range_search(start, end))
                }
                SingleIndex::Hash { .. } => {
                    Err(Error::index("哈希索引不支持范围查询".to_string()))
                }
            }
        } else {
            Err(Error::index(format!("索引 {} 不存在", index_name)))
        }
    }
    
    /// 复合索引范围查询
    pub fn range_lookup_composite(
        &mut self,
        index_name: &str,
        start_values: Vec<Value>,
        end_values: Vec<Value>,
    ) -> Result<Vec<usize>> {
        if let Some(index) = self.composite_indexes.get_mut(index_name) {
            index.range_lookup(start_values, end_values)
        } else {
            Err(Error::index(format!("复合索引 {} 不存在", index_name)))
        }
    }
    
    /// 前缀查询（仅复合B+树索引支持）
    pub fn prefix_lookup_composite(
        &mut self,
        index_name: &str,
        prefix_values: Vec<Value>,
    ) -> Result<Vec<usize>> {
        if let Some(index) = self.composite_indexes.get_mut(index_name) {
            index.prefix_lookup(prefix_values)
        } else {
            Err(Error::index(format!("复合索引 {} 不存在", index_name)))
        }
    }
    
    /// 删除索引
    pub fn drop_index(&mut self, name: &str) -> Result<()> {
        let removed = self.single_indexes.remove(name).is_some() 
            || self.composite_indexes.remove(name).is_some();
        
        if removed {
            self.update_stats();
            Ok(())
        } else {
            Err(Error::index(format!("索引 {} 不存在", name)))
        }
    }
    
    /// 获取所有索引名称
    pub fn list_indexes(&self) -> Vec<String> {
        let mut names = Vec::new();
        names.extend(self.single_indexes.keys().cloned());
        names.extend(self.composite_indexes.keys().cloned());
        names
    }
    
    /// 获取索引信息
    pub fn get_index_info(&self, name: &str) -> Result<IndexInfo> {
        if let Some(index) = self.single_indexes.get(name) {
            let (index_type, columns) = match index {
                SingleIndex::BTree { column, .. } => ("btree".to_string(), vec![column.clone()]),
                SingleIndex::Hash { column, .. } => ("hash".to_string(), vec![column.clone()]),
            };
            
            Ok(IndexInfo {
                name: name.to_string(),
                index_type,
                columns,
                is_composite: false,
            })
        } else if let Some(index) = self.composite_indexes.get(name) {
            let index_type = match index.index_type() {
                CompositeIndexType::BTree => "composite_btree".to_string(),
                CompositeIndexType::Hash => "composite_hash".to_string(),
            };
            
            Ok(IndexInfo {
                name: name.to_string(),
                index_type,
                columns: index.columns().to_vec(),
                is_composite: true,
            })
        } else {
            Err(Error::index(format!("索引 {} 不存在", name)))
        }
    }
    
    /// 获取统计信息
    pub fn get_stats(&self) -> &IndexManagerStats {
        &self.stats
    }
    
    /// 更新统计信息
    fn update_stats(&mut self) {
        self.stats.single_indexes = self.single_indexes.len();
        self.stats.composite_indexes = self.composite_indexes.len();
        self.stats.total_indexes = self.stats.single_indexes + self.stats.composite_indexes;
    }
    
    /// 优化所有索引
    pub fn optimize_all(&mut self) -> Result<()> {
        // 对于哈希索引，可以进行压缩
        for index in self.single_indexes.values_mut() {
            if let SingleIndex::Hash { index: hash, .. } = index {
                hash.shrink_to_fit()?;
            }
        }
        
        tracing::info!("索引优化完成");
        Ok(())
    }
    
    /// 验证所有索引的完整性
    pub fn validate_all(&self) -> Result<()> {
        for (name, index) in &self.single_indexes {
            match index {
                SingleIndex::BTree { index: btree, .. } => {
                    btree.validate().map_err(|e| {
                        Error::index(format!("B+树索引 {} 验证失败: {}", name, e))
                    })?;
                }
                SingleIndex::Hash { index: hash, .. } => {
                    hash.validate().map_err(|e| {
                        Error::index(format!("哈希索引 {} 验证失败: {}", name, e))
                    })?;
                }
            }
        }
        
        tracing::info!("所有索引验证通过");
        Ok(())
    }
}

/// 索引信息
#[derive(Debug, Clone)]
pub struct IndexInfo {
    /// 索引名称
    pub name: String,
    /// 索引类型
    pub index_type: String,
    /// 列名列表
    pub columns: Vec<String>,
    /// 是否为复合索引
    pub is_composite: bool,
}

impl Default for IndexManager {
    fn default() -> Self {
        Self::new()
    }
}
